#pragma once

#include <iostream>
#include <string>
#include <strings.h>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
const int gnum=1024;

namespace Client
{
    using namespace std;

    class udpClient
    {
    public:
        udpClient(const string &serverip, const uint16_t &serverport) 
        : severip_(serverip),severport_(serverport), sockfd_(-1), quit_(false) {}
        void initClient()
        {
            // 创建socket
            sockfd_ = socket(AF_INET, SOCK_DGRAM, 0);
            if (sockfd_ == -1)
            {
                cerr << "socket error: " << errno << " : " << strerror(errno) << endl;
                exit(2);
            }
            cout << "socket success: " << " : " << sockfd_ << endl;

        }
        void run()
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_addr.s_addr = inet_addr(severip_.c_str()); //sin_addr是个结构体 其内s_addr是用于存储IPv4地址 是uint32_t类型变量
            server.sin_port = htons(severport_);

            //string message;
            char buffer[gnum];
            while(!quit_)
            {
                cout << "Please Enter# ";
                cin.getline(buffer,gnum);

                // 避免发送空行（仅包含换行符的输入）
                if (strlen(buffer) == 0)
                continue;
                                //待发送消息缓冲区 消息长度 
                sendto(sockfd_, buffer, strlen(buffer), 0, (struct sockaddr*)&server, sizeof(server));
            }
        }
        ~udpClient() {}

    private:
        int sockfd_;
        string severip_;
        uint16_t severport_;
        bool quit_;
    };
} 
